package websocket.service.impl;

import java.io.IOException;

import org.apache.log4j.Logger;

import websocket.constant.Status;
import websocket.pojo.Message;
import websocket.service.BaseMsgHandleService;
import websocket.service.HistoryMsgService;
import websocket.socket.MyWebSocket;
import websocket.socket.SocketContext;
import websocket.util.CommonUtil;

public class CommonMsgHandleImpl implements BaseMsgHandleService {
	private static final Logger logger = Logger
			.getLogger(CommonMsgHandleImpl.class.getName());

	@Override
	public void handle(Message message, MyWebSocket socket) {
		switch (message.getStatus()) {
		case Status.MSG_TEXT:
			HistoryMsgService service = new HistoryMsgServiceImpl();
			service.addHistory(message);// 将聊天信息记录到历史记录中去
			this.sendMsg(message);
			break;
		case Status.MSG_SHAKE:
			this.sendMsg(message);
			break;
		default:
			break;
		}
	}

	@Override
	public void sendMsg(Message message) {
		MyWebSocket socket = SocketContext.getInstance().getSocket(
				message.getTarget());
		try {
			if (socket != null && socket.getConn().isOpen()) {
				socket.getConn().sendMessage(
						CommonUtil.handleMsgToJSON(message));
			} else {
				// TODO 说明好友不在线，那么将会把这个消息转入离线消息
			}
		} catch (IOException e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}

}
